feat: register Discord command groups - #9445
Open
casama233 wants to merge 2 commits into
Open
Conversation
This was referenced Jul 29, 2026
Contributor
|
未来还需要增加对VUE面板的支持功能,也得加入议程,辛苦 |
Contributor
Author
|
感谢提醒,也谢谢关注这个方向 🙏 我刚又对了一下目前 master 的实现:Dashboard 的插件详情页现在已经能读取并树状展示 command group / subcommands,所以这部分基础支持目前已经具备了。 #9445 这次我先把范围聚焦在 Discord 原生 Slash Command 的注册映射,尽量避免把前端改动混在同一个 PR 里。如果后续 Vue 面板还有更具体的交互或配置需求,也很欢迎指出,我可以再单独跟进补齐。 |
casama233
marked this pull request as ready for review
August 11, 2026 01:43
Contributor
There was a problem hiding this comment.
Hey - I've found 2 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/platform/sources/discord/discord_platform_adapter.py" line_range="565" />
<code_context>
+ Returns:
+ Whether the name can be registered with Discord.
+ """
+ return name == name.lower() and bool(re.match(r"^[-_'\w]{1,32}$", name))
+
+ @staticmethod
</code_context>
<issue_to_address>
**issue (bug_risk):** Slash command name validator allows characters Discord likely rejects (single quote), causing potential registration failures.
The regex `^[-_'\w]{1,32}$` currently allows single quotes, but Discord’s documented pattern only permits lowercase letters, digits, underscores, and hyphens (e.g. `^[a-z0-9_-]{1,32}$` or `^[\w-]{1,32}$` with the existing lowercase check). This mismatch means we may accept command names that Discord rejects with 400s at registration. Please align the regex with Discord’s constraints so invalid names are caught locally.
</issue_to_address>
### Comment 2
<location path="astrbot/core/platform/sources/discord/discord_platform_adapter.py" line_range="627" />
<code_context>
+ parent=parent,
+ )
+
+ def _create_slash_command_group(
+ self,
+ group_filter: CommandGroupFilter,
</code_context>
<issue_to_address>
**issue (complexity):** Consider further refactoring `_create_slash_command_group` by extracting small helpers for path formatting, option limits, and name validation to flatten control flow and reduce duplication.
The new helpers already reduce some duplication, but `_create_slash_command_group` still has tightly nested control flow and repeated validation/logging logic. You can simplify it further with small utilities without changing behavior.
### 1. Centralize command path formatting
Right now the command path is inlined multiple times:
```py
f"{root_name} {child_name}"
f"{root_name} {child_name} {leaf_name}"
```
Introduce a tiny formatter and use it everywhere:
```py
@staticmethod
def _format_command_path(*parts: str) -> str:
return " ".join(parts)
```
Then update your uses:
```py
path = self._format_command_path(root_name, child_name)
logger.warning(
f"[Discord] Skipping invalid or duplicate entry '{path}'."
)
leaf_path = self._format_command_path(root_name, child_name, leaf_name)
logger.warning(
f"[Discord] Skipping invalid or duplicate entry '{leaf_path}'."
)
```
This reduces noise and makes intent clearer.
### 2. Extract option‑limit checks into a helper
The `_DISCORD_MAX_OPTIONS` limit and related logging is duplicated for root group and subgroup. You can centralize this:
```py
def _can_add_option(
self,
group: discord.SlashCommandGroup,
path: str,
) -> bool:
if len(group.subcommands) >= _DISCORD_MAX_OPTIONS:
logger.warning(
f"[Discord] Command group '{path}' exceeds "
f"{_DISCORD_MAX_OPTIONS} options; remaining entries were skipped."
)
return False
return True
```
Use it in both loops:
```py
for child_filter in group_filter.sub_command_filters:
if not self._can_add_option(root_group, root_name):
break
...
for leaf_filter in child_filter.sub_command_filters:
subgroup_path = self._format_command_path(root_name, child_name)
if not self._can_add_option(subgroup, subgroup_path):
break
...
```
Now both limit checks share the same behavior and wording.
### 3. Extract shared name/duplicate validation
You have similar logic for root vs subgroup:
```py
if (
not self._is_valid_slash_command_name(child_name)
or child_name in root_names
):
...
if (
not self._is_valid_slash_command_name(leaf_name)
or leaf_name in subgroup_names
):
...
```
This can be consolidated into a small helper that also handles logging:
```py
def _is_valid_unique_name(
self,
name: str,
used: set[str],
path: str,
) -> bool:
if not self._is_valid_slash_command_name(name) or name in used:
logger.warning(
f"[Discord] Skipping invalid or duplicate entry '{path}'."
)
return False
return True
```
Then the loops become flatter:
```py
child_path = self._format_command_path(root_name, child_name)
if not self._is_valid_unique_name(child_name, root_names, child_path):
continue
...
leaf_path = self._format_command_path(root_name, child_name, leaf_name)
if not self._is_valid_unique_name(leaf_name, subgroup_names, leaf_path):
continue
```
This pulls validation and logging out of the nested control flow, making `_create_slash_command_group` easier to read while preserving all behavior.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
casama233
force-pushed
the
feat/discord-command-groups
branch
from
August 13, 2026 08:46
6474be9 to
ad992f0
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Relates to #9258.
Note
This is a Draft proposal for maintainer feedback. It does not migrate any plugin commands by itself and is not requesting immediate merge.
Discord currently skips
CommandGroupFilterand every childCommandFilterduring application command registration. Plugins that use AstrBot command groups therefore have no discoverable Discord slash command, while plugins that flatten their command tree can consume a large part of Discord's application command quota.The proposed mapping was discussed in #9258 before implementation:
#9258 (comment)
A separate Draft plugin migration demonstrates the intended consumer without coupling its review or merge to this core PR:
vmoranv-reborn/astrbot_plugin_pixiv_reborn#48
Modifications / 改动点
CommandGroupFilteras one PycordSlashCommandGroup.paramsstring on each leaf command. This avoids overlapping with the separate typed-option work in Discord 适配器增强功能 #9125.command -> subcommand group -> subcommand.Scope boundary:
Existing flattened plugin commands are not rewritten or removed.
Plugins opt in only by using AstrBot's existing
command_groupdecorators.This PR is independent of the Pixiv authentication PR and can be reviewed on its own.
No new dependency is introduced.
This is NOT a breaking change. / 这不是一个破坏性变更。
Screenshots or Test Results / 运行截图或测试结果
Verification steps:
Result:
GitHub Actions also pass across the repository test suite, build, format check,
CodeQL, and startup smoke tests on Ubuntu, macOS, and Windows with Python
3.10–3.14.
The generated payload was also checked with the real Pycord classes. A root group with one direct command and one nested group serializes as:
The two leaf callbacks rebuild
pixiv search <params>andpixiv user detail <params>respectively.Checklist / 检查清单
😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
/ 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
/ 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in
requirements.txtandpyproject.toml./ 我确保没有引入新依赖库,或者引入新依赖库的同时将其添加到
requirements.txt和pyproject.toml文件相应位置。😮 My changes do not introduce malicious code.
/ 我的更改没有引入恶意代码。
Summary by Sourcery
Register AstrBot command groups as structured Discord slash commands while preserving existing command handling behavior.
New Features:
Enhancements:
Tests: